﻿namespace TfsReportRenderer.ImageAdder
{
    using System.IO;
    using System.Linq;

    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;

    /// <summary>
    /// A post generation step to insert images into the Excel file.
    /// </summary>
    public class AddImage : PostGenerationSteps
    {
        /// <summary>
        /// The memory stream with the binary data of an image.
        /// </summary>
        private readonly MemoryStream imageStream;

        /// <summary>
        /// Initializes a new instance of the <see cref="AddImage"/> class.
        /// </summary>
        /// <param name="row"> The row position for the image. </param>
        /// <param name="col"> The column position of the image. </param>
        /// <param name="sheet"> The sheet to insert the image. </param>
        /// <param name="imageStream"> The image data stream (must be of format PNG). </param>
        public AddImage(int row, int col, string sheet, MemoryStream imageStream)
            : base(row, col, sheet)
        {
            this.imageStream = imageStream;
        }

        /// <summary>
        /// Applies the insertion of the image into the excel file.
        /// </summary>
        /// <param name="documentFile"> The document file path and name. </param>
        public override void Apply(string documentFile)
        {
            this.imageStream.Seek(0, SeekOrigin.Begin);
            var fileName = Path.GetTempFileName();
            File.WriteAllBytes(fileName, this.imageStream.ToArray());
            using (var document = SpreadsheetDocument.Open(documentFile, true))
            {
                var id = document.WorkbookPart.Workbook.Sheets.Elements<Sheet>().Where(s => s.Name == this.Sheet).Select(x => x.Id.Value).FirstOrDefault()
                      ?? document.WorkbookPart.Workbook.Sheets.Elements<Sheet>().Select(x => x.Id.Value).First();

                var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(id);
                OpenXmlTool.InsertImage(worksheetPart, fileName, 1, 1, 200, 200, 20, 10);
            }

            File.Delete(fileName);
        }
    }
}